package main

import (
	"bytes"
	"fmt"
	"os"
	"path/filepath"

	"github.com/sirupsen/logrus"
)

type MyFormatter struct {
}

func main() {
	// 设置级别
	logrus.SetLevel(logrus.DebugLevel)
	logrus.SetReportCaller(true)
	logrus.SetFormatter(&MyFormatter{})
	logrus.Printf("我是一条日志 %s", "ok")
	logrus.Info("我是一条日志", " test")
	file, _ := os.OpenFile("./1.log", os.O_CREATE|os.O_WRONLY, 0666)
	logrus.SetOutput(file)
	logrus.Printf("我是一条日志 %s", "ok")
	logrus.Debug("我是一条日志", " debug")
	logrus.Info("我是一条日志", " test")
	logrus.Warn("我是一条日志", " test")
	logrus.Error("我是一条日志", " test")
	test()
}

func test() {
	logrus.Warn("我是一条日志", " warn")
	testMap := make(map[int]int)
	testMap[1] = 1
	if testMap[1] == 1 {
		logrus.Warn("map true", " warn")
	}
	if testMap[2] != 1 {
		logrus.Warnf("map false + %v" , testMap[2])
	}
}

func (m *MyFormatter) Format(entry *logrus.Entry) ([]byte, error) {
	var newLog string
	var b *bytes.Buffer
	if entry.Buffer != nil {
		b = entry.Buffer
	} else {
		b = &bytes.Buffer{}
	}

	timestamp := entry.Time.Format("2006-01-02 15:04:05")
	//HasCaller()为true才会有调用信息
	if entry.HasCaller() {
		fName := filepath.Base(entry.Caller.File)
		newLog = fmt.Sprintf("[%s %s] [%s:%d] %s\n",
			timestamp, entry.Level, fName, entry.Caller.Line, entry.Message)
	} else {
		newLog = fmt.Sprintf("[%s %s] %s\n", timestamp, entry.Level, entry.Message)
	}

	b.WriteString(newLog)
	return b.Bytes(), nil
}
